package com.cloud.config;

import org.springframework.stereotype.Component;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

@Component
public class ScriptEnginePool {
    
    private final Queue<ScriptEngine> enginePool;
    private final ScriptEngineManager manager;
    private final int poolSize = 100;  // 创建100个ScriptEngine实例

    public ScriptEnginePool() {
        this.manager = new ScriptEngineManager();
        this.enginePool = new ConcurrentLinkedQueue<>();
        initializePool();
    }

    // 初始化池，预创建ScriptEngine实例
    private void initializePool() {
        for (int i = 0; i < poolSize; i++) {
            ScriptEngine engine = manager.getEngineByName("python");
            enginePool.offer(engine);
        }
    }

    // 从池中获取一个ScriptEngine实例
    public ScriptEngine acquireEngine() {
        return enginePool.poll();  // 从队列中获取一个实例
    }

    // 归还ScriptEngine实例到池中
    public void releaseEngine(ScriptEngine engine) {
        enginePool.offer(engine);  // 将实例放回队列中
    }
}